package com.ytsky.mybatis.demo;

import com.ytsky.mybatis.demo.entity.Customer;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用jdbc进行数据库访问
 *
 */
public class JdbcDemo {
    public static void main(String[] args) throws SQLException {
        //1.定义连接参数和sql语句
        String username="root";
        String password="123456";
        String url="jdbc:mysql://localhost:3306/db_quote?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai";
      String sql="select * from db_quote.tb_customer";

      //2.创建数据库连接
      final  Connection connection = DriverManager.getConnection(url, username, password);
     //3.创建SQL执行对象
      final   PreparedStatement preparedStatement = connection.prepareStatement(sql);
     //4.执行SQL语句。查询数据库，并返回查询得到的结果
      final  ResultSet resultSet  = preparedStatement.executeQuery();
     //5.遍历结果集，将查询数据分装对象中
        List<Customer> customers=new ArrayList<>();
        while (resultSet.next()){
            //将一条数据装入到新的customer
            Customer customer=new Customer();
            customer.setId(resultSet.getInt(1));
            customer.setName(resultSet.getString(2));
            customer.setTel(resultSet.getString(3));
            customer.setAddress(resultSet.getString(4));
            customer.setRelName(resultSet.getString(5));
            customer.setOther(resultSet.getString(6));
         //将这个新的数据的Customer对象添加到内存集合中
            customers.add(customer);
       }

    //数据保存内存之后就可以使用这些数据
        System.out.println(customers);
        //关闭资源
        resultSet.close();
        preparedStatement.close();
        connection.close();

    }
}
